const express = require("express");
const minimist = require("minimist");

const fs = require("fs");
const path = require("path");

const app = express();
const args = minimist(process.argv.slice(2));

function listFilesSync(dir) {
	let results = [];
	let files = fs.readdirSync(dir);
	files.forEach(file => {
		const fullPath = path.join(dir, file);
		const stat = fs.statSync(fullPath);
		if (stat.isFile()) {
			results.push(fullPath);
		} else if (stat.isDirectory()) {
			// 如果需要递归处理子目录，可以添加递归调用逻辑在这里
			results = results.concat(listFilesSync(fullPath)); // 递归调用自身来处理子目录中的文件
		}
	});
	return results;
}

console.log("args", args);

const server = "127.0.0.1";
const port = args.port || 6100;
const root = args.root || "E:/DCM/webdicom-test-dcm";

const allowedOrigins = ["http://localhost:8080", "http://127.0.0.1:8080"];

app.use((req, res, next) => {
	const origin = req.headers.origin;
	if (allowedOrigins.includes(origin)) {
		// 设置允许的来源
		res.setHeader("Access-Control-Allow-Origin", origin);
		// 允许携带 Cookie
		res.setHeader("Access-Control-Allow-Credentials", "true");
		// 允许的请求方法
		res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		// 允许的请求头
		res.setHeader(
			"Access-Control-Allow-Headers",
			"Content-Type, Authorization, X-Requested-With"
		);
		// 预检请求结果缓存时间，单位秒
		res.setHeader("Access-Control-Max-Age", "86400");
	}
	// 预检请求直接返回
	if (req.method === "OPTIONS") {
		return res.sendStatus(200);
	}

	next();
});

app.use(express.static(root));

app.get("/dicomurl/:user", (req, res) => {
	const rootDir = "E:/DCM/webdicom-test-dcm/";
	const user = req.params.user;
	const dir = path.join(rootDir, user);

	const files = listFilesSync(dir);
	const fileList = files.map(file => {
		const relativePath = file.replaceAll("\\", "/").replace(rootDir, "");
		return `http://${server}:${port}/${relativePath}`;
	});

	console.log("query: /dicomurl/" + req.params.user, "files count:", fileList.length);

	res.send(fileList);
});

app.listen(port, () => {
	console.log("port", port);
	console.log("root", root);
	console.log(`Server url http://localhost:${port}`);
});
